package FlereKommunikationTestDevice;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lejos.nxt.Button;
import lejos.nxt.ButtonListener;
import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import lejos.nxt.comm.NXTConnection;

public class FKTD {

	public static void main(String [] args) throws IOException, InterruptedException
	{  
		Button.ESCAPE.addButtonListener(new ButtonListener() {
			@Override public void buttonReleased(Button b) { System.exit(0); }
			@Override public void buttonPressed(Button b) {}
		});

		String connected = "Connected";
		String waiting = "Waiting...";
		String closing = "Closing...";  

		int messageLength = 0;
		String message = "";

		while(true)
		{
			LCD.drawString(waiting,0,0);
			LCD.refresh();

			BTConnection btc = Bluetooth.waitForConnection();

			LCD.clear();
			LCD.drawString(connected,0,0);
			LCD.refresh(); 		

			DataInputStream dis = btc.openDataInputStream();
			DataOutputStream dos = btc.openDataOutputStream();
			
			int messageCount = 0;

			while (true) 
			{
				messageLength = dis.readInt();
				
				//exit besked
				if(messageLength == -1) break;

				//laver beskeden
				for(int i = 0; i < messageLength; i++)
				{
					message += dis.readChar();
				}

				//skriver beskeden 
				if(message.length() > 0)
				{
					LCD.drawString("" + message,0,1);		
				}
				
				message = "";
				
				//sender hvor mange beskeder der er blevet modtaget i denne forbindelse op til nu
				dos.writeInt(++messageCount);
				dos.flush();
			}

			//Lukker alting
			dis.close();
			dos.close();
			Thread.sleep(100); // wait for data to drain
			LCD.clear();
			LCD.drawString(closing,0,0);
			LCD.refresh();
			btc.close();
			LCD.clear();
		}

	}
}
